package com.javawork.juc.one;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author zhangxiaolu
 * @date 2023-02-05 21:33
 */
public class CompletableFutureApi2Demo {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("111");
            return 1;
//        }, threadPool).thenApply(f -> {
        }, threadPool).handle((f, e) -> {
            //handle 会带着异常继续走，就像finally
            int i = 1 / 0;//thenApply 会直接结束
            System.out.println("222");
            return f + 2;
        }).handle((f, e) -> {
//        }).thenApply(f -> {
            System.out.println("333");
            return f + 3;
        }).whenComplete((v, e) -> {
            if (e == null) {
                System.out.println("-----计算结果：" + v);
            }
        }).exceptionally(e -> {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        });

        System.out.println(Thread.currentThread().getName() + "----主线程先去忙其他的");
        //主线程不能立马结束，否则默认的线程池会关闭，可以自己创建一个线程池然后主动关闭避免该问题。
        threadPool.shutdown();
    }
}
